package com.itmuch.core.jsr349;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.util.StringUtils;

public class MobileNotNecessaryValidator implements ConstraintValidator<MobileNotNecessary, String> {
    @Override
    public void initialize(MobileNotNecessary constraintAnnotation) {
    }

    @Override
    public boolean isValid(String mobile, ConstraintValidatorContext context) {
        if (mobile == null) {
            return true;
        }

        if (StringUtils.hasText(mobile)) {
            Pattern pattern = Pattern.compile("^[1][34578][0-9]{9}$");
            Matcher matcher = pattern.matcher(mobile);
            if (!matcher.matches()) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("手机号格式错误.").addConstraintViolation();
                return false;
            }
        }

        return true;
    }
}
